package com.sxc.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;

@WebServlet("/cookie04")
public class Cookie04 extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 使用URLEncoder进行编码
        String name = "姓名";
        String value = "张三";
        name = URLEncoder.encode(name);
        value = URLEncoder.encode(value);
        // 创建Cookie对象
        Cookie cookie1 = new Cookie(name, value);
        resp.addCookie(cookie1);

        //获取Cookie
        Cookie[] cookies = req.getCookies();
        if(cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                String dname = URLDecoder.decode(cookie.getName());
                String dvalue = URLDecoder.decode(cookie.getValue());
                System.out.println("dname: " + dname);
                System.out.println("dvalue: " + dvalue);
            }
        }
    }
}
